const API = require('../../utils/api')
const pathUrl = require('../../utils/common.js')
Page({
  data: {
    courts: [],
    searchKey: '',
    currentCategory: 'all',
    currentSort: 'distance',
    priceRange: [0, 200],
    selectedTypes: [],
    selectedFacilities: [],
    placeType: [
      { name: '红土', value: '红土' },
      { name: '硬土', value: '硬土' },
      { name: '草地', value: '草地' }
    ],
    facilities: [
      { name: '休息区', value: '休息区' },
      { name: '卫生间', value: '卫生间' },
      { name: '储物柜', value: '储物柜' },
      { name: '淋浴室', value: '淋浴室' },
      { name: '饮用水', value: '饮用水' }
    ],
    page: 1,
    hasMore: true,
    loading: false,
    refreshing: false
  },
  onLoad() {
    this.loadCourts()
  },
  onShow() {
  },
  async loadCourts(reset = true) {
    // 如果当前正在加载中，避免重复加载
    if (this.data.loading) return
    if (reset) {
      this.setData({ page: 1, hasMore: true })
    }
    if (!this.data.hasMore && !reset) return
    this.setData({ loading: true })
    try {
      let queryForm = {
        keyWords: this.data.searchKey,
        orderType: this.data.currentSort,
        pageNum: this.data.page,
        pageSize: 10
      }
      let res = await API.nearByPlaceList(queryForm)
      const newCourts = res.records || [];
      // 处理图片URL路径
      for(let i=0; i<newCourts.length; i++){
        if(newCourts[i].image) {
          newCourts[i].image = pathUrl + newCourts[i].image;
        }
      }
      console.log("==============",newCourts)
      // 根据返回的数据量判断是否还有更多数据
      const hasMoreData = newCourts.length === 10
      
      this.setData({
        courts: reset ? newCourts : [...this.data.courts, ...newCourts],
        page: this.data.page + 1,
        hasMore: hasMoreData,
        loading: false,
        refreshing: false
      })
    } catch (err) {
      console.error('加载场地信息失败:', err)
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
      this.setData({ loading: false, refreshing: false })
    }
  },
  onSearchInput(e) {
    console.log(e.detail.value)
    this.setData({ searchKey: e.detail.value })
    this.loadCourts()
  },
  onSearch() {
    this.loadCourts()
  },
  changeSort(e) {
    const sort = e.currentTarget.dataset.sort
    this.setData({ currentSort: sort })
    this.loadCourts()
  },


  goToCourtDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/court-detail/court-detail?id=${id}`
    })
  },

  quickBook(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/booking/booking?courtId=${id}`
    })
  },

  // 原生下拉刷新处理函数
  onPullDownRefresh() {
    this.loadCourts(true).finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 兼容原有的scroll-view刷新
  onRefresh() {
    this.loadCourts()
  },

  loadMore() {
    this.loadCourts(false)
  },

  onShareAppMessage() {
    return {
      title: '发现附近的优质网球场地',
      path: '/pages/courts/courts',
      imageUrl: '/images/share-court.jpg'
    }
  }
})